package com.heba.greenmulu.login;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.heba.ATApp;
import com.heba.AppManager;
import com.heba.Cfg;
import com.heba.Debug;
import com.heba.config.CommonConfig;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.MainActivity;
import com.heba.greenmulu.R;
import com.heba.helper.FileUploadHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.helper.TakePhotoHelper;
import com.heba.helper.callback.FileUploadListener;
import com.heba.permission.PermissionHelper;
import com.heba.popupwindow.PhotoPopupWindow;
import com.heba.utils.CommonUtils;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.heba.utils.ImageTools;
import com.heba.utils.StatusBarUtils;
import com.heba.utils.ToastShow;
import com.tencent.cos.xml.CosXmlServiceConfig;
import com.tencent.cos.xml.CosXmlSimpleService;
import com.tencent.qcloud.core.auth.QCloudCredentialProvider;
import com.tencent.qcloud.core.auth.ShortTimeCredentialProvider;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.io.FileNotFoundException;

import cn.jpush.android.api.JPushInterface;

/**
 * 注册完善信息页面
 * Created by jason on 2019/2/12.
 */

public class SignUpNewActivity extends BaseActivity {

    public static final int TYPE_SOCIAL_LOGIN = 1001;    //微信、facebook

    private ConstraintLayout topbar;
    private View view_background;
    private ImageView iv_avatar;
    private EditText et_account, et_name, et_email, et_password, et_re_password;
    private TextView tv_account_tips, tv_email_tips, tv_password_tips;
    private ImageView img_agreement;
    private TextView txt_agreement;
    private Button btn_sign_up;

    /**
     * 头像上传
     */
    private PhotoPopupWindow photoPopupWindow;
    private File tempFile;   //头像保存路径
    private int crop = 500;  //裁剪大小
    private String pictureUrl = "";   //上传图片地址

    /**
     * 腾讯云文件存储对象
     */
    private CosXmlServiceConfig serviceConfig;
    private CosXmlSimpleService cosXmlSimpleService;
    private String appid = "1253933048";
    private String region = "ap-guangzhou";

    private String title;
    private String name;
    private String email;
    private int type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置状态栏透明
        StatusBarUtils.setStatusBar(this);
        setContentView(R.layout.activity_signup_new);
        initTopbar();
        findViewById();
        setContentTextView();
        setTopbarPadding();
        initView();
        initCosClient();
        initPopWindow();
    }

    /**
     * 初始化PopupWindow
     */
    private void initPopWindow() {
        /**
         * 照片弹出框
         */
        photoPopupWindow = new PhotoPopupWindow(this, ViewGroup.LayoutParams.MATCH_PARENT, DensityUtils.dip2px(this, 165));

        photoPopupWindow.setOnPhotoPopupClickListener(new PhotoPopupWindow.OnPhotoPopupClickListener() {
            @Override
            public void onCameraClick() {
                tempFile = ImageTools.createFile(ImageTools.getUploadPathFolder(), ImageTools.getFileName());
                TakePhotoHelper.takePicture((Activity) mContext, tempFile);
            }

            @Override
            public void onAlbumClick() {
                tempFile = ImageTools.createFile(ImageTools.getUploadPathFolder(), ImageTools.getFileName());
                TakePhotoHelper.selectPhoto((Activity) mContext);
            }

            @Override
            public void onCancelClick() {

            }
        });

        photoPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_background.setVisibility(View.GONE);
            }
        });

    }

    /**
     * 初始化cosClient
     */
    private void initCosClient() {
        //初始化 cosClient
        serviceConfig = new CosXmlServiceConfig.Builder().setAppidAndRegion(appid, region).setDebuggable(true).builder();
        /**
         * 初始化对象，来给SDK提供临时密钥。
         */
        QCloudCredentialProvider credentialProvider = new ShortTimeCredentialProvider(ATApp.CosSecretId,
                ATApp.CosSecretKey, 300);
        cosXmlSimpleService = new CosXmlSimpleService(this, serviceConfig, credentialProvider);
    }

    @Override
    protected void findViewById() {
        topbar = findViewById(R.id.topbar);
        view_background = findViewById(R.id.view_background);
        img_agreement = findViewById(R.id.img_agreement);
        txt_agreement = findViewById(R.id.txt_agreement);
        btn_sign_up = findViewById(R.id.btn_sign_up);
        btn_sign_up.setForceDarkAllowed(false);
    }

    /**
     * Let topbar to extend to status bar.
     *
     * @notice this method have to be used after setContentView.
     */
    private void setTopbarPadding() {
        // Set the padding to match the Status Bar height
        topbar.setPadding(0, StatusBarUtils.getStatusBarHeight(this), 0, 0);
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            name = bundle.getString(CommonConfig.SIGNUP_FIRSTNAME, "");
            title = bundle.getString(CommonConfig.SIGNUP_TITLE, "");
            pictureUrl = bundle.getString(CommonConfig.SIGNUP_ICON, "");
            email = bundle.getString(CommonConfig.SIGNUP_EMAIL, "");
            type = bundle.getInt(CommonConfig.TYPE, 0);
        }
        if (Cfg.Language == 1) {
            txt_agreement.setText(Html.fromHtml(getResources().getString(R.string.agreement) + "<br/>" + "<a href='" + Cfg.TermsUseUrl + "'style='color:#a7e163'>" +
                    getResources().getString(R.string.term_of_use) + "</a>" + getResources().getString(R.string.and) +
                    "<a href='" + Cfg.PrivacyUrl + "'style='color:#a7e163'>" + getResources().getString(R.string.privacy_policy) + "</a>"));
        } else {
            txt_agreement.setText(Html.fromHtml(getResources().getString(R.string.agreement) + "<a href='" + Cfg.TermsUseUrl + "'style='color:#a7e163'>" +
                    getResources().getString(R.string.term_of_use) + "</a>" + getResources().getString(R.string.and) +
                    "<a href='" + Cfg.PrivacyUrl + "'style='color:#a7e163'>" + getResources().getString(R.string.privacy_policy) + "</a>"));
        }

        //设置为可点击模式
        txt_agreement.setMovementMethod(LinkMovementMethod.getInstance());
        txt_title.setText(title);

        /**
         * 显示数据
         */
        et_name.setText(name);
        et_email.setText(email);
        GlideUtil.loadImageWithPlaceHolderID(this, pictureUrl, iv_avatar, R.drawable.icon_head_portrait);

        /**
         * 头像
         */
        iv_avatar.setOnClickListener(v -> {
            view_background.setVisibility(View.VISIBLE);
            getCameraPermission();
        });

        /**
         * 协议checkbox
         */
        img_agreement.setOnClickListener((View v) -> img_agreement.setSelected(img_agreement.isSelected() ? false : true));

        /**
         * 注册事件监听
         */
        btn_sign_up.setOnClickListener(v -> {
            signUp();
        });

        et_account.setHint(getResources().getString(R.string.sign_up_enter_user_id));
        et_name.setHint(getResources().getString(R.string.sign_up_enter_name));
        et_email.setHint(getResources().getString(R.string.sign_up_enter_email));
        et_password.setHint(getResources().getString(R.string.sign_up_enter_password));
        et_re_password.setHint(getResources().getString(R.string.sign_up_enter_re_password));
        et_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        et_re_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

        //设置account只允许输入字母和数字
        et_account.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_SUBJECT);
//        et_account.setKeyListener(DigitsKeyListener.getInstance("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
        et_account.addTextChangedListener(new clearTextWatcher());
        et_email.addTextChangedListener(new clearTextWatcher());
        et_re_password.addTextChangedListener(new clearTextWatcher());
        clearTextTips();
    }

    /**
     * 清除提示文字
     */
    private class clearTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            clearTextTips();
        }
    }

    /**
     * 设置文字
     */
    private void setContentTextView() {
        int[] viewIDs = new int[]{R.id.view_photo, R.id.view_account, R.id.view_name, R.id.view_email,
                R.id.view_password, R.id.view_repassword};
        String[] strTexts = getResources().getStringArray(R.array.sign_up_datas);
        for (int i = 0; i < viewIDs.length; i++) {
            findContentTextView(viewIDs[i], strTexts[i]);
        }
    }

    /**
     * findContentTextView
     *
     * @param viewID
     * @param text
     */
    private void findContentTextView(int viewID, String text) {
        View view = findViewById(viewID);
        TextView textView = view.findViewById(R.id.textview);
        textView.setText(text);

        switch (viewID) {
            case R.id.view_photo:
                iv_avatar = view.findViewById(R.id.iv_avatar);
                break;
            case R.id.view_account:
                et_account = view.findViewById(R.id.et_text);
                tv_account_tips = view.findViewById(R.id.tv_text2);
                tv_account_tips.setText(getResources().getString(R.string.sign_up_account_used_tips));
                break;
            case R.id.view_name:
                et_name = view.findViewById(R.id.et_text);
                break;
            case R.id.view_email:
                et_email = view.findViewById(R.id.et_text);
                tv_email_tips = view.findViewById(R.id.tv_text2);
                tv_email_tips.setText(getResources().getString(R.string.sign_up_email_used_tips));
                break;
            case R.id.view_password:
                et_password = view.findViewById(R.id.et_text);
                break;
            case R.id.view_repassword:
                et_re_password = view.findViewById(R.id.et_text);
                tv_password_tips = view.findViewById(R.id.tv_text2);
                tv_password_tips.setText(getResources().getString(R.string.sign_up_password_same_tips));
                break;
            default:
                break;
        }
    }

    /**
     * signUp
     */
    private void signUp() {
        if (!img_agreement.isSelected()) {
            ToastShow.displayToast(this, getResources().getString(R.string.sign_up_agreement_tips));
            return;
        }

        if (TextUtils.isEmpty(et_account.getText()) || TextUtils.isEmpty(et_name.getText())
                || TextUtils.isEmpty(et_email.getText()) || TextUtils.isEmpty(et_password.getText())
                || TextUtils.isEmpty(et_re_password.getText()) || et_password.getText().toString().trim().isEmpty()
                || et_re_password.getText().toString().trim().isEmpty()) {
            ToastShow.displayToast(this, getResources().getString(R.string.sign_up_message_tips));
            return;
        }

        if (et_account.getText().toString().length() < 6) {
            ToastShow.displayToast(this, getResources().getString(R.string.sign_up_account_input_tips));
            return;
        }

        if (!CommonUtils.isEmail(et_email.getText().toString())) {
            ToastShow.displayToast(this, getResources().getString(R.string.email_input_tips));
            return;
        }

        if (!et_password.getText().toString().equals(et_re_password.getText().toString())) {
            clearTextTips();
            tv_password_tips.setVisibility(View.VISIBLE);
            return;
        }
        String registrationID = JPushInterface.getRegistrationID(this);
        progressDialog.show();
        if (type == SignUpNewActivity.TYPE_SOCIAL_LOGIN) {
            //facebook、微信完善信息
            //微信、facebook注册完善资料
            new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                @Override
                public void Success() {
                    progressDialog.dismiss();

                    progressDialog.show();
                    new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                        @Override
                        public void Success() {
                            progressDialog.dismiss();
                            AppManager.getAppManager().finishAllActivity();
                            openActivity(MainActivity.class);
                        }

                        @Override
                        public void Fail(String error) {
                            progressDialog.dismiss();
                        }
                    }).getUserInfo(mContext);
                }

                @Override
                public void Fail(String error) {
                    progressDialog.dismiss();
                    if (error.equals("ERR_ACCOUNT_EXIST")) {
                        clearTextTips();
                        tv_account_tips.setVisibility(View.VISIBLE);
                        return;
                    }
                    if (error.equals("ERR_EMAIL_EXIST")) {
                        clearTextTips();
                        tv_email_tips.setVisibility(View.VISIBLE);
                        return;
                    }
                }
            }).setUserInfoNew(this, pictureUrl, et_account.getText().toString(), et_name.getText().toString(),
                    et_email.getText().toString(), et_password.getText().toString(),registrationID);
        } else {
            //邮箱注册
            new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                @Override
                public void Success() {
                    progressDialog.dismiss();
                    AppManager.getAppManager().finishAllActivity();
                    openActivity(MainActivity.class);
                }

                @Override
                public void Fail(String error) {
                    progressDialog.dismiss();
                    if (error.equals("ERR_ACCOUNT_EXIST")) {
                        clearTextTips();
                        tv_account_tips.setVisibility(View.VISIBLE);
                        return;
                    }
                    if (error.equals("ERR_EMAIL_EXIST")) {
                        clearTextTips();
                        tv_email_tips.setVisibility(View.VISIBLE);
                        return;
                    }
                }
            }).emailSignupNew(mContext, pictureUrl, et_account.getText().toString(), et_name.getText().toString(),
                    et_email.getText().toString(), et_password.getText().toString(),registrationID);
        }
    }

    /**
     * 清除提示文字
     */
    private void clearTextTips() {
        tv_account_tips.setVisibility(View.INVISIBLE);
        tv_password_tips.setVisibility(View.INVISIBLE);
        tv_email_tips.setVisibility(View.INVISIBLE);
    }

    /**
     * 获取摄像头,读取文件权限
     */
    private void getCameraPermission() {
        new PermissionHelper(mContext, new PermissionHelper.PermissionListener() {
            @Override
            public void onPermissionSuccess() {
                photoPopupWindow.showAtLocation(iv_avatar, Gravity.BOTTOM, 0, 0);
            }

            @Override
            public void onPermissionFailure() {

            }
        }).requestPermission(Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA);
    }

    /**
     * --------------------------- 相册或拍照获取图片部分 ----------------------------------
     */

    /**
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TakePhotoHelper.TAKE_PICTURE:
                    // 拍照裁剪图片
                    TakePhotoHelper.cropImage((Activity) mContext, tempFile, Uri.fromFile(tempFile), crop,
                            TakePhotoHelper.PICTURE_SEND);
                    break;

                case TakePhotoHelper.CHOOSE_PICTURE:
                    // 相册选取图片去裁剪
                    if (data != null) {
                        TakePhotoHelper.cropImage((Activity) mContext, tempFile, data.getData(), crop,
                                TakePhotoHelper.PICTURE_SEND);
                    }
                    break;

                case TakePhotoHelper.PICTURE_SEND:
                    if (tempFile != null)
                        sentPicToNext(tempFile);
                    break;

                default:
                    break;
            }
        }
    }

    /**
     * 将进行剪裁后的图片传递到下一个界面上
     *
     * @param file
     */
    private void sentPicToNext(File file) {
        //解决小米系统 retuen data 为null的问题
        try {
            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.fromFile(file)));
            //图片路径
            String localPath = ImageTools.savePhotoToSDCard(this, bitmap, ImageTools.getUploadPathFolder(), ImageTools.getFileName(), false);
            String cosPath = "greenmulu/image/transfer_" + ImageTools.getFileName();
            if (bitmap != null) {
                /**
                 * 上传图片处理
                 */
                loading.Start();
                new FileUploadHelper(this).upload(localPath, cosPath, new FileUploadListener() {
                    @Override
                    public void onSuccess(String imgUrl) {
                        /**
                         * 上传成功
                         */
                        runOnUiThread(() -> {
                            loading.End();
                            pictureUrl = imgUrl;
                            GlideUtil.loadImageWithPlaceHolderID(mContext, pictureUrl, iv_avatar, R.drawable.icon_head_portrait);
                        });
                    }

                    @Override
                    public void onFail() {
                        /**
                         * 上传失败
                         */
                        runOnUiThread(() -> {
                            loading.End();
                        });
                    }
                });
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Debug.Log("清理上传图片的文件夹", ImageTools.getUploadPathFolder().toString());
        //清理文件图片
        ImageTools.deleteAllPhoto(ImageTools.getUploadPathFolder());
    }
}
